package com.empire.module.member.service.mapconfig;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.empire.framework.security.core.util.SecurityFrameworkUtils;
import com.empire.framework.web.core.util.WebFrameworkUtils;
import com.empire.module.member.dal.dataobject.user.MemberUserDO;
import com.empire.module.member.dal.dataobject.warnconfigpersonrelation.WarnConfigPersonRelationDO;
import com.empire.module.member.dal.mysql.user.MemberUserMapper;
import com.empire.module.member.dal.mysql.warnconfigpersonrelation.WarnConfigPersonRelationMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import com.empire.module.member.controller.admin.mapconfig.vo.*;
import com.empire.module.member.dal.dataobject.mapconfig.MapConfigDO;
import com.empire.framework.common.pojo.PageResult;
import com.empire.framework.common.util.object.BeanUtils;

import com.empire.module.member.dal.mysql.mapconfig.MapConfigMapper;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.empire.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.empire.module.member.enums.ErrorCodeConstants.*;

/**
 * 地图配置主 Service 实现类
 *
 * @author 主席大人
 */
@Service
@Validated
public class MapConfigServiceImpl implements MapConfigService {

    @Resource
    private MapConfigMapper mapConfigMapper;
    @Resource
    private MemberUserMapper memberUserMapper;
    @Resource
    private WarnConfigPersonRelationMapper warnConfigPersonRelationMapper;

    @Override
    public String createMapConfig(MapConfigSaveReqVO createReqVO) {
        // 插入
        MapConfigDO mapConfig = BeanUtils.toBean(createReqVO, MapConfigDO.class);
        mapConfigMapper.insert(mapConfig);
        // 返回
        return mapConfig.getId();
    }

    @Override
    public void updateMapConfig(MapConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateMapConfigExists(updateReqVO.getId());
        // 更新
        MapConfigDO updateObj = BeanUtils.toBean(updateReqVO, MapConfigDO.class);
        mapConfigMapper.updateById(updateObj);
    }

    // 删除配置（级联删除多边形和顶点）
    @Override
    @Transactional
    public void deleteMapConfig(String id) {
        // 校验存在
        validateMapConfigExists(id);
        // 删除
        mapConfigMapper.deleteById(id);
    }

    private void validateMapConfigExists(String id) {
        if (mapConfigMapper.selectById(id) == null) {
            throw exception(MAP_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public MapConfigDO getMapConfig(String id) {
        return mapConfigMapper.selectById(id);
    }

    @Override
    public PageResult<MapConfigDO> getMapConfigPage(MapConfigPageReqVO pageReqVO) {
        pageReqVO.setCreateDeptId(SecurityFrameworkUtils.getLoginUserDeptId());
        String idNumber = pageReqVO.getIdNumber();
        // 如果要搜索证件号码
        if (StrUtil.isNotEmpty(idNumber)) {
            List<String> configIdList = getConfigIdByIdNumber(idNumber);
            if (!configIdList.isEmpty()) {
                pageReqVO.setIdList(configIdList);
            }else {
                // 返回空
                return new PageResult<>(new ArrayList<>(), 0L);
            }
        }
        IPage<MapConfigDO> mapConfigPage = mapConfigMapper.selectPage(pageReqVO);
        return new PageResult<>(mapConfigPage.getRecords(), mapConfigPage.getTotal());

    }

    /**
     * 查询证件号码对应的配置ID
     *
     * @param idNumber 证件号码
     * @return 配置Id集合
     */
    @Override
    public List<String> getConfigIdByIdNumber(String idNumber){
        List<String> configIdList = new ArrayList<>();
        if (StrUtil.isNotEmpty(idNumber)) {
            List<Long> personIdList = memberUserMapper.selectByIdNumber(idNumber);
            if (!personIdList.isEmpty()) {
                LambdaQueryWrapper<WarnConfigPersonRelationDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(WarnConfigPersonRelationDO::getPersonId, personIdList);
                List<WarnConfigPersonRelationDO> relations = warnConfigPersonRelationMapper.selectList(queryWrapper);
                if (!relations.isEmpty()) {
                    configIdList = relations.stream().map(WarnConfigPersonRelationDO::getWarnConfigId).distinct().
                            collect(Collectors.toCollection(ArrayList::new));
                }
            }
        }
        return configIdList;
    }

    @Override
    public List<MapConfigDO> getConfigSelect(WarnConfigListVo reqVO) {
        reqVO.setCreateDeptId(SecurityFrameworkUtils.getLoginUserDeptId());
        String idNumber = reqVO.getIdNumber();
        // 如果要搜索证件号码
        if (StrUtil.isNotEmpty(idNumber)) {
            List<Long> personIdList = memberUserMapper.selectByIdNumber(idNumber);
            if (!personIdList.isEmpty()) {
                LambdaQueryWrapper<WarnConfigPersonRelationDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(WarnConfigPersonRelationDO::getPersonId, personIdList);
                List<WarnConfigPersonRelationDO> relations = warnConfigPersonRelationMapper.selectList(queryWrapper);
                if (!relations.isEmpty()) {
                    reqVO.setIdList(relations.stream().map(WarnConfigPersonRelationDO::getWarnConfigId).distinct().
                            collect(Collectors.toCollection(ArrayList::new)));
                }
            }

        }
        return mapConfigMapper.getConfigSelect(reqVO);

    }

}